//拦截白名单
import NProgress from "@/util/NprogressUtil";
import { useUserStore } from "@/store";
import router from "@/router";
import { NavigationGuardNext, RouteLocationNormalized } from "vue-router";
import { UserTypeEnum } from "@/types/UserTypeEnum";
import { ElMessageBox } from "element-plus";

//免登录白名单
const whiteList = ["/basic", "/register", "/home", "/type", "/search"];
router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const userStore = useUserStore();
  document.title = `${to.meta.title} | 云选购物`;
  const hasToken = userStore.token;
  if (!hasToken) {
    if (isWhite(to.path)) {
      next(); // 在白名单，直接进入
      return;
    }
    await ElMessageBox.confirm(
      "您访问的页面需要登录才能使用，请问是否前往登录?",
      "警告",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    )
      .then(() => {
        // 未登录,跳转到登录页
        redirectToLogin(to, next);
      })
      .catch(() => {
        next({ ...from });
      });

    return;
  }
  // 有token，已登录
  if (!userStore.userInfo.id) {
    //没有用户数据，请求用户数据
    try {
      //获取登录用户信息
      await userStore.getUserInfo();
      next({ ...to, replace: true });
    } catch (error) {
      NProgress.done();
    }
  }

  //有toke，访问的是登录页面，跳转到首页
  if (to.path === "/basic/login") {
    // 如果已登录，跳转到首页
    next({ path: getHomePathByRole() });
    return;
  }
  //访问的是首页，根据用户权限调整到前台还是后台
  if (to.path === "/") {
    // 如果已登录，跳转到首页
    next({ path: getHomePathByRole() });
    return;
  }
  // 获取权限信息
  const role: any = userStore.userInfo?.role;
  // 不是用户角色访问"/"，返回到后台
  if (
    (to.path === "/" || to.path === "/home" || !to.path.includes("backend")) &&
    role > UserTypeEnum.USER
  ) {
    next({ path: "/backend", replace: true });
  }
  //获取路由最小权限
  const minRole: any = to.meta?.minRole;
  //没有权限限制
  if (!minRole) {
    next(); // 在白名单，直接进入
    return;
  }
  //低于最小权限，没有权限，回到当前页面
  if (role < minRole) {
    next({ path: "/basic/403" });
  } else {
    //判断是否只有一个权限
    const oneRole = to.meta?.role;
    if (oneRole && role !== oneRole) {
      next({ path: "/basic/403" });
      return;
    }
    next();
  }
});

//是否在白名单内
function isWhite(path: string) {
  return whiteList.filter((item) => path.includes(item)).length > 0;
}

/** 重定向到登录页 */
function redirectToLogin(
  to: RouteLocationNormalized,
  next: NavigationGuardNext
) {
  //获取路径参数
  const params = new URLSearchParams(
    to.query as Record<string, string>
  ).toString();
  //拼接重定向路径
  const redirect = params ? `${to.path}?${params}` : to.path;
  next(`/basic/login?redirect=${encodeURIComponent(redirect)}`);
}

router.afterEach(() => {
  NProgress.done();
});

function getHomePathByRole() {
  const userStore = useUserStore();
  const role = userStore.userInfo.role;
  if (role && role !== UserTypeEnum.USER) {
    return "/backend";
  }
  return "/home";
}

export { getHomePathByRole };
export default router;
